<?php

namespace App\Models;

use Illuminate\Support\Facades\DB;
use Session;
use Cookie;

class Order extends BaseModel
{
    protected $table = "order";

    const PREFIX = 'ag_';


    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 按条件查询单条数据
     */
    public function getOne(array $where, $fields = '*')
    {
        return $this->multiSelect($fields)->multiWhere($where)->first();
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    //查询需要excel导出的字段
    public function getExcel(array $where = [], $fields = '*', $order = '')
    {
        return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order);
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getExcel2(array $where = [], $fields = '*', $order = '', $page = 1, $pageSize = self::PAGESIZE)
    {
        $offset = ($page * $pageSize) - $pageSize;
        $data = $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)
            ->skip($offset)->take($pageSize)->get();
        if ($data) {
            $data = $data->toArray();
        }
        $arr['nextpage'] = $page + 1;
        $arr['data'] = $data;
        return $arr;
    }


    /**
     * 根据条件删除数据
     */
    public function del(array $where)
    {
        return $this->multiWhere($where)->delete();
    }

    /**
     *插入数据
     */
    public function add($data)
    {
//        dd($data);
        return $this->insertGetId($data);
    }

    /**
     *更新数据
     */
    public function up($where, $data)
    {
        return $this->multiWhere($where)->update($data);
    }

    /**
     * 获取和
     */
    public function getSum($where, $field)
    {
        return $this->multiWhere($where)->sum($field);
    }

    /**
     * 字段递加
     */
    public function inc($where, $field, $n)
    {
        return $this->multiWhere($where)->increment($field, $n);
    }

    /**
     * 统计数据个数
     */
    public function getCount($where)
    {
        return $this->multiWhere($where)->count();
    }

    /**
     * 获取分销列表
     */
    public function getFxData()
    {
        $aid = session('agent')['aid'];
        $agent = new Agent();
        $data = $agent->getList(array('pid' => $aid));
        $orderlist = [];
        if ($data) {
            $data = $data->toArray();
            $agent_id = array();
            foreach ($data as $v) {
                $agent_id[] .= $v['id'];
            }
            $where['aid'] = ['in', $agent_id];
            $order['id'] = "desc";
            $orderlist = $this->getList($where);
        }
        return $orderlist;
    }

    public function getAgentOrderList($request)
    {
        $where['aid'] = $request['id'];
        if ($request['starttime'] && $request['endtime']) {
            $where['created_at'] = ['between', [$request['starttime'], $request['endtime']]];
        }
        //dd($where);
        $order['id'] = 'desc';
        $rows = $this->getList($where, '*', $order, 10);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 10);
        }
        return $rows;
    }

    /**
     * 订单列表
     * @param $request
     * @return mixed
     */
    public function getOrderList($request)
    {
        $keyword = $request['keyword'] ? $request['keyword'] : '';
        if ($keyword) {
            $where['order_sn'] = ['like', '%' . $keyword . '%'];
        }
        $agent = new Agent();
        $res = $agent->getDingjiAgentList(session('adminId'));
        if (empty($res[0])) {
            return '';
        }
        $aids = [];
        foreach ($res as $v) {
            $aids[] = $v['id'];
        }
        $where['aid'] = ['in', $aids];
        if (session('adminId')) {
            $where['bid'] = session('adminId');
        } else {
            $where['aid'] = session('adminId');
        }

        $start = date("Y-m-d", strtotime($request['starttime']));
        $end = date("Y-m-d", strtotime($request['endtime']));
        $start1 = $start;
        $end1 = $end;
        if ($start > $end) {
            $start1 = $end;
            $end1 = $start;
        }
        if ($request['starttime'] && $request['endtime']) {
            $where['created_at'] = ['glt', [['>', $start1], ['<=', $end1]]];;
        }
        $state = $request['status'];    //0未发货,1已发货,2待确认
        //dd($state);
        if ($state) {
            $where['status'] = $state;
        } else {
            $where['status'] = 0;
        }
        $order['id'] = 'desc';
        //dd($where);
        $rows = $this->getList($where, '*', $order, 10);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 10);
        }
        //dd($rows);
        return $rows;
    }

    /**
     * 订单列表
     * @param $request
     * @return mixed
     */
    public function getLevOneOrderList($request)
    {
        $agent = new Agent();
        $condition['bid'] = session('adminId');
        $condition['lev'] = session('adminId');
        $agentList = $agent->getAgentList(['bid']);
        $keyword = $request['keyword'] ? $request['keyword'] : '';
        $where['bid'] = session('adminId');
        if ($keyword) {
            $where['order_sn'] = ['like', '%' . $keyword . '%'];
        }

        $start = date("Y-m-d", strtotime($request['starttime']));
        $end = date("Y-m-d", strtotime($request['endtime']));
        $start1 = $start;
        $end1 = $end;
        if ($start > $end) {
            $start1 = $end;
            $end1 = $start;
        }
        if ($request['starttime'] && $request['endtime']) {
            $where['created_at'] = ['glt', [['>', $start1], ['<=', $end1]]];;
        }
        $state = $request['status'];    //0未发货,1已发货,2待确认
        //dd($state);
        if ($state) {
            $where['status'] = $state;
        } else {
            $where['status'] = 0;
        }
        $order['id'] = 'desc';
        //dd($where);
        $rows = $this->getList($where, '*', $order, 10);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 10);
        }
        return $rows;
    }


    /**
     * @param $request
     * @return mixed
     * 确认发货
     */
    public function chageOrderStatus($request)
    {

        $where['id'] = $request['id'];
        $data['status'] = 1;

        //验证内容是否为空
        if (empty($request['sms']) || empty($request['Courier_number'])) {
            $ajaxData['msg'] = '快递信息不能为空！';
            return $ajaxData;
            exit();
        }

        $data['shipping_company'] = $request['sms'];  //快递公司
        $data['shipping_code'] = $request['Courier_number'];  //快递单号


        $res = $this->up($where, $data);
        $ajaxData['status'] = $res ? 1 : 0;
        $ajaxData['msg'] = '发货成功！';
        if (!$res) {
            $ajaxData['msg'] = '发货失败！';
        }
        return $ajaxData;
    }

    // 改变订单状态
    public function getChangeState($request)
    {
        $where['id'] = $request['id'];
        $data['status'] = 2;
        $res = $this->up($where, $data);
        $ajaxData['status'] = $res ? 1 : 0;
        $ajaxData['msg'] = '操作成功！';
        if (!$res) {
            $ajaxData['msg'] = '操作失败！';
        }
        return $ajaxData;
    }

    // 改变订单状态
    public function deleteOrder($request)
    {
        $where['id'] = $request['id'];
        $order = $this->getOne($where);
        if ($order['status'] > 0) {
            return ['status' => 0, 'msg' => '非法操作!'];
        }
        $res = $this->del($where);
        $ajaxData['status'] = $res ? 1 : 0;
        $ajaxData['msg'] = '操作成功！';
        if (!$res) {
            $ajaxData['msg'] = '操作失败！';
        }
        return $ajaxData;
    }

    //
    public function orderTotal($request)
    {
        $aid = session('agent')['aid'];
        $agent = new Agent();
        $data = $agent->getList(array('pid' => $aid));
        if (!$data) {
            return 0;
        }
        $agent_id = array();
        foreach ($data as $v) {
            $agent_id[] .= $v['id'];
        }
        $where['aid'] = ['in', $agent_id];
        $start = 0;
        $end = 0;
        if ($request['start']) {
            $start = strtotime($request['start']) - 3600 * 8;
        }
        if ($request['end']) {
            $end = strtotime($request['end']) + 3600 * 16 - 1;
        }
        if (!$start && !$end) {
            return 0;
        }
        $where['addtime'] = ['between', [$start, $end]];
        $order['id'] = "desc";
        return $this->getSum($where, 'pay_money');
    }

    // 统计订单信息
    public function OrderCount()
    {
//          $order = DB::select("select DATE_FORMAT(created_at,'%Y%u') weeks,created_at,count(id) count from ag_order group by weeks");
//          $data['title'] = "交易统计";
//          $data['time'] = ['周一','周二','周三','周四','周五','周六','周日'];
//          $data['data'] = [1300,500,800,100,600,1200,2500];
//          return $data;

        //按月查找
        $sql = "select count(d.id) as num, DATE_FORMAT(d.created_at,'%m')  as month from ag_order d GROUP by DATE_FORMAT(d.created_at,'%m') ORDER BY month ASC ";
        $data = DB::select($sql);
        //dd($data);
        $str = '[';
        foreach ($data as $k => $v) {

            $str .= "['$v->month',$v->num],";

        }
        $str = rtrim($str, ',');
        $str .= ']';
        return $str;

    }

    public function addOrder($request)
    {
        $goods = new Goods();
        $goodsInfo = $goods->getGoodsInfoById($request['gid']);
        $agent = new Agent();
        $levInfo = $agent->getAgentLevRateById(session('agent')['aid'], $goodsInfo['bid']);
        $data['order_sn'] = createOrderNo();
        $data['aid'] = session('agent')['aid'];
        $data['bid'] = session('agent')['bid'];
        $data['goods_id'] = $request['gid'];
        $data['goods_name'] = $goodsInfo['name'];
        $data['goods_num'] = $request['num'];
        $data['goods_price'] = $goodsInfo['price'];
        $data['discount'] = $levInfo['discount'];
        $data['total_money'] = $request['num'] * $goodsInfo['price'];
        $data['pay_money'] = $data['total_money'];
        if ($levInfo['discount'] && $levInfo['discount'] <= 100 && $levInfo['discount'] >= 0) {
            $data['pay_money'] = ceil($data['total_money'] * $data['discount'] / 100);
        }
        $data['name'] = $request['name'];
        $data['mobile'] = $request['mobile'];
        $data['address'] = $request['address'];
        $data['remark'] = $request['remark'] ? $request['remark'] : '';
        $data['addtime'] = time();
        $data['created_at'] = date('Y-m-d H:i:s', time());
        $data['updated_at'] = date('Y-m-d H:i:s', time());
        $res = $this->add($data);
        $returnData['status'] = $res ? 1 : 0;
        $returnData['msg'] = '下单成功！';
        if (!$res) {
            $returnData['msg'] = '下单失败！';
        }
        return $returnData;
    }

    public function checkOrderData($request)
    {
        $returnData['status'] = 0;
        if (!$request['gid'] || !$request['num']) {
            $returnData['msg'] = '参数错误！';
            return $returnData;
        }
        if (!$request['name'] || !$request['mobile'] || !$request['address']) {
            $returnData['msg'] = '姓名、手机号和地址必须填写！';
            return $returnData;
        }
        $returnData['status'] = 1;
        return $returnData;
    }

    /**
     * 订单列表
     * @param $request
     * @return mixed
     */
    public function getMyOrderList($request)
    {
        $ordersn = $request['ordersn'] ? $request['ordersn'] : '';
        $where['aid'] = session('agent')['aid'];
        if ($ordersn) {
            $where['order_sn'] = $ordersn;
        }
        $order['id'] = 'desc';
        $rows = $this->getList($where, '*', $order, 10);
        return $rows;
    }

    public function getOrderInfoById($id)
    {
        return $this->getOne(['id' => $id]);
    }

    public function checkOrderSn($orderSn)
    {
        if (!$orderSn) {
            return ['status' => 400];
        }
        $res = $this->getOne(['order_sn' => $orderSn]);
        if (!$res) {
            return ['status' => 400];
        }
        return ['status' => 200];
    }


    public function sendNextLevOrder($request)
    {
        $orderSn = $request['QueryKey'];
        if (!$request['QueryKey']) {
            return ['status' => 400, 'msg' => '请输入订单号'];
        }
        $codeList = $request['code'];
        $orderInfo = $this->getOne(['order_sn' => $orderSn]);
        if (!$orderInfo) {
            return ['status' => 400, 'msg' => '该订单号不存在'];
        }
        if ($orderInfo['status']) {
            return ['status' => 400, 'msg' => '该订单已发货'];
        }
        $security = new Securitycodeout();
        if (!session('agent')['pid']) {
            $security = new Securitycodein();
        }
        $where['bid'] = $orderInfo['bid'];
        $where['code'] = ['in', $codeList];
        $codeInfo = $security->getList($where, 'code');
        if (!count($codeInfo)) {
            return ['status' => 400, 'msg' => '该订单号没有绑定防伪码，无法继续操作'];
        }
        $codeInfo = $codeInfo->toArray();
        $newCodes = [];
        foreach ($codeInfo as $v) {
            $newCodes[] = $v['code'];
        }
        foreach ($codeList as $v) {
            if (!in_array($v, $newCodes)) {
                return ['status' => 400, 'msg' => '防伪码[' . $v . ']不存在'];
            }
        }
        return ['status' => 200, 'msg' => '请填写物流信息', 'id' => $orderInfo['id'], 'codeList' => $codeList];
    }

    public function sendGoods($request)
    {
        $where['id'] = $request['id'];
        $orderInfo = $this->getOne($where);
        if (!$orderInfo) {
            return ['status' => 400, 'msg' => '该订单不存在'];
        }
        if ($orderInfo['status']) {
            return ['status' => 400, 'msg' => '该订单已发货'];
        }
        $data['shipping_company'] = $request['shipping_company'];
        $data['shipping_code'] = $request['shipping_code'];
        $data['status'] = 1;
        $this->start();
        try {
            $a = $this->up($where, $data);
            $condition['code'] = ['in', $request['codeList']];
            $securityOut = new Securitycodeout();
            $securityIn = new Securitycodein();
            if (!session('agent')['pid']) {
                $outData = [];
                foreach($request['codeList'] as $v) {
                    $outData[] = [
                        'bid' => session('agent')['bid'],
                        'order_id' => $request['id'],
                        'code' => $v,
                        'order_num' => $orderInfo['goods_num'],
                        'created_at' => date("Y-m-d H:i:s"),
                        'updated_at' => date("Y-m-d H:i:s")
                    ];
                }
               $b =  $securityOut->addAll($outData);
               $c = $securityIn->del($condition);
            } else {
                $d = $securityOut->up($condition, ['order_id' => $request['id']]);
            }
            $this->commit();
            return ['status' => 200, 'msg' => '发货成功'];
        } catch (\Exception $e) {
            $this->rollback();
            return ['status' => 400, 'msg' => '发货失败'];
        }
    }

    //获取订单详细信息
    public function getOrderDetail($request)
    {
        $data = $this->getOne(['id'=>$request['id']]);
        return $data;
    }



}